package com.keyinong.qudan.view;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;
import com.keyinong.fragment.MyorderFragment;
import com.keyinong.fragment.MyorderweiFragment;
import com.keyinong.fragment.ShezhiFragment;
import com.keyinong.fragment.ShouyeFragment;
import com.keyinong.qudan.R;
import com.keyinong.qudan.ScanActivity;
import com.keyinong.qudan.entity.OrderEntity;
import com.keyinong.qudan.tools.HttpTools;
import com.keyinong.qudan.tools.MyFragmentReplace;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.umeng.message.ALIAS_TYPE;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.umeng.message.proguard.k.e;

public class MainActivity extends FragmentActivity {
	private static String TAG = MainActivity.class.getSimpleName(); 	
	PowerManager pm=null;
	WakeLock mWakeLock=null;
	/**扫一扫*/
	private ImageButton btn_saoyisao;
//	/**上下拉刷新*/
//	private PullToRefreshListView list_order;
	HttpTools httpTools = null;
	private ArrayList<OrderEntity> orderlist;
	
	int page = 10;
	int offset = 0;
	private String token;
	private String state;
	
	/** 首页 */
	private RadioButton rb_shouye;
	/** 未接单 */
	private RadioButton rb_weijiedan;
	/** 已接单 */
	private RadioButton rb_yijiedan;
	/** 已接单 */
	private RadioButton rb_shezhi;

	private int IS_CURRENT_PAGE = 1;
	/**未接单数*/
	private TextView tv_num;
	
	// 语音合成对象
	private SpeechSynthesizer mTts;
	// 默认发音人
	private String voicer = "xiaoyan";
	private String[] mCloudVoicersEntries;
	private String[] mCloudVoicersValue ;
	private Toast mToast;
	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;

	private SharedPreferences mSharedPreferences;
	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag"); 
		// in onResume() call

		// in onPause() call 



		//这里填写的内容就是会被 朗读的内容
		//		TTs();
		//		String sayContext = "您有新的订单请及时处理";
		//		int code = mTts.startSpeaking(sayContext, mTtsListener);
		////		/** 
		////		 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
		////		 * text:要合成的文本，uri:需要保存的音频全路径，listener:回调接口
		////		*/
		////		String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
		////		int code = mTts.synthesizeToUri(text, path, mTtsListener);
		//		
		//		if (code != ErrorCode.SUCCESS) {
		//			if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
		//				//未安装则跳转到提示安装页面
		//				//mInstaller.install();
		//			}else {
		//				showTip("语音合成失败,错误码: " + code);	
		//			}
		//		}

		//	mInstaller = new  ApkInstaller(TtsDemo.this);
//		WebView wb=(WebView)findViewById(R.id.wb_dingdan);
//		wb.getSettings().setJavaScriptEnabled(true);  
//		wb.getSettings().setDomStorageEnabled(true);  
//		SharedPreferences sp = getSharedPreferences("spReg",
//				Context.MODE_PRIVATE);
//		token = sp.getString("token", "");
//		Log.i("zq", "token--"+token);
//		String url="http://mlo.jishi88.com/index.php#!/adminorders?token=";
//		Log.i("zq", "url--"+url+token);
//		String url2= url+token;
//		wb.setWebViewClient(new WebViewClient(){
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				// TODO Auto-generated method stub
//				return super.shouldOverrideUrlLoading(view, url);
//			}
//		});
//		wb.loadUrl(url2);
		btn_saoyisao=(ImageButton)findViewById(R.id.btn_saoyisao);
		btn_saoyisao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), ScanActivity.class);
				startActivity(intent);
			}
		});
		orderlist = new ArrayList<OrderEntity>();
//		list_order=(PullToRefreshListView)findViewById(R.id.list_order);
//		list_order.setMode(Mode.BOTH);
//		list_order.setOnRefreshListener(onrefresh);
		myOrder();
		tv_num = (TextView)findViewById(R.id.tv_num);
		rb_shouye = (RadioButton)findViewById(R.id.rb_shouye);
		rb_weijiedan = (RadioButton)findViewById(R.id.rb_weijiedan);
		rb_yijiedan = (RadioButton)findViewById(R.id.rb_yijiedan);
		rb_shezhi = (RadioButton)findViewById(R.id.rb_shezhi);
		setRbOnClick();
		ShouyeFragment home = new ShouyeFragment();
		MyFragmentReplace.fragmentReplace(MainActivity.this,
				R.id.fram_fanqiedingcan, home);
		//友盟推送服务
//		UmengPush();

		//		//这是后台朗读，实例化一个SynthesizerPlayer
		//        SynthesizerPlayer player = SynthesizerPlayer.createSynthesizerPlayer(BluetoothActivity.this, APPID);
		//        //设置语音朗读者，可以根据需要设置男女朗读，具体请看api文档和官方论坛
		//        player.setVoiceName("vivixiaoyan");//在此设置语音播报的人选例如：vivixiaoyan、vivixiaomei、vivixiaoqi
		//        player.playText("您有新的订单，请及时处理", "ent=vivi21,bft=5",null);
		// 云端发音人名称列表
		//				mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
		//				mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);
		//						
		//				mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, MODE_PRIVATE);
		//		            // 移动数据分析，收集开始合成事件
		//					FlowerCollector.onEvent(BluetoothActivity.this, "tts_play");
		//					
		//					// 设置参数
		//					setParam();
		//					int code = mTts.startSpeaking("您有新的订单，请及时处理", mTtsListener);
		//					if (code != ErrorCode.SUCCESS) {
		//						if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
		//							//未安装则跳转到提示安装页面
		////							mInstaller.install();
		//						}else {
		//							showTip("语音合成失败,错误码: " + code);	
		//						}
		//					}
	}
	
	private void setRbOnClick() {
		rb_shouye.setOnClickListener(rbOnClickListener);
		rb_weijiedan.setOnClickListener(rbOnClickListener);
		rb_yijiedan.setOnClickListener(rbOnClickListener);
		rb_shezhi.setOnClickListener(rbOnClickListener);
	}
	
	private OnClickListener rbOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			// 首页
			case R.id.rb_shouye:
				if (IS_CURRENT_PAGE != 1) {
					ShouyeFragment home = new ShouyeFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, home);
					IS_CURRENT_PAGE = 1;
				}
				break;
			// 未接单
			case R.id.rb_weijiedan:
				if (IS_CURRENT_PAGE != 2) {
					MyorderweiFragment oftenbuy = new MyorderweiFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, oftenbuy);
					IS_CURRENT_PAGE = 2;
					
				}
				break;
			// 已接单
			case R.id.rb_yijiedan:
				if (IS_CURRENT_PAGE != 3) {
					MyorderFragment order = new MyorderFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, order);
					IS_CURRENT_PAGE = 3;
				}
				break;
			case R.id.rb_shezhi:
				if (IS_CURRENT_PAGE != 4) {
					ShezhiFragment shezhi = new ShezhiFragment();
					MyFragmentReplace.fragmentReplace(MainActivity.this,
							R.id.fram_fanqiedingcan, shezhi);
					IS_CURRENT_PAGE = 4;
				}
				break;

			default:
				break;
			}

		}
	};
	
	
	
	private Handler handler = new Handler();
	private Runnable runnable = new Runnable() {
		public void run() {
			try {
				this.update();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			handler.postDelayed(this, 10000);// 间隔60秒刷新一次
		}
		void update() throws IOException {
//			onrefresh.onPullDownToRefresh(list_order);
			myOrder();
		}
	}; 
//	
//	public void updateUnreadLabel() throws IOException {
//
//		Process mLogcatProc = null;  
//		BufferedReader reader = null;  
//			//获取logcat日志信息  
//			mLogcatProc = Runtime.getRuntime().exec(new String[] { "logcat","com.umeng.message.proguard.l:I *:S" });  
//			reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));  
//			String line = reader.readLine();  
////			String ceshi=reader.readLine();
//			Log.i("zq", "line--"+line);
//			
////			while ((line = reader.readLine()) != null) {  
////				Log.i("zq", "ceshi---"+reader.readLine());
//				Log.i("zq", "hhh");
//				if (line.indexOf("status code : 200") > 0) {  
//					//logcat打印信息在这里可以监听到  
//					// 使用looper 把给界面一个显示  
//					Looper.prepare();  
//					TTs();
//					Toast.makeText(BluetoothActivity.this, "监听到log信息", Toast.LENGTH_SHORT).show();   
//					Looper.loop();  
//				}  				
////			}  
//	}
	
//	/** 上下拉刷新 */
//	private OnRefreshListener2<ListView> onrefresh = new OnRefreshListener2<ListView>() {
//
//		@Override
//		public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
//			offset = 0;
//			orderlist.clear();
//			httpTools.order(token, page + "", offset + "", new JsonMyOrder());
//		}
//
//		@Override
//		public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//			offset += page;
//			httpTools.order(token, page + "", offset + "", new JsonMyOrder());
//			// setSection();
//			// adapter.notifyDataSetChanged();
//		}
//
//	};
	private void myOrder() {
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("token", "");
		if (httpTools == null) {
			httpTools = new HttpTools(MainActivity.this);
		}
		httpTools.order(token, page + "", offset + "", "1","0",new JsonMyOrder());
	}
	
	private class JsonMyOrder extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			try {
				boolean code = response.getBoolean("code");
				if (code == true) {
					JSONObject object = response.getJSONObject("data");
//					String isnew = object.getString("isnew");
					JSONArray array = object.getJSONArray("orders");
					for (int i = 0; i < array.length(); i++) {
						JSONObject object2 = array.getJSONObject(i);
						String id = object2.getString("id");
						String receive_time = object2.getString("receive_time");
						state = object2.getString("state");
						String name = object2.getString("name");
						String phone = object2.getString("phone");
						String address = object2.getString("address");
						String recmode = object2.getString("recmode");
						orderlist.add(new OrderEntity(id, receive_time, state, name, phone, address,recmode));
					}
					if(array.length()==0){
						tv_num.setVisibility(View.GONE);
						tv_num.setText("0");
					}else {
						tv_num.setVisibility(View.VISIBLE);
						tv_num.setText(""+array.length());
					}
						
				} else {
					String msg = response.getString("msg");
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				}
//				list_order.onRefreshComplete();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub

		super.onStart();
		// 初始化合成对象
		mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);

		// 云端发音人名称列表
		mCloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
		mCloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);

		mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT);

		setParam();
		/**开启线程用于监听log输出的信息**/ 
		handler.postDelayed(runnable, 10000);
//		new Thread(new Runnable() {  
//
//			@Override  
//			public void run() {  
//
//				Process mLogcatProc = null;  
//				BufferedReader reader = null;  
//				try {  
//					//获取logcat日志信息  
//					mLogcatProc = Runtime.getRuntime().exec(new String[] { "logcat","com.umeng.message.proguard.l:I *:S" });  
//					reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));  
//					String line;  
////					String ceshi=reader.readLine();
//					
//					
//					while ((line = reader.readLine()) != null) {  
////						Log.i("zq", "ceshi---"+reader.readLine());
//						Log.i("zq", "hhh");
//						if (line.indexOf("status code : 200") > 0) {  
//							//logcat打印信息在这里可以监听到  
//							// 使用looper 把给界面一个显示  
//							Looper.prepare();  
//							TTs();
//							Toast.makeText(BluetoothActivity.this, "监听到log信息", Toast.LENGTH_SHORT).show();   
//							Looper.loop();  
//						}  
//						
//					}  
//				} catch (Exception e) {  
//					e.printStackTrace();  
//				}  
//			}  
//		}).start();   

	}
	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		@Override
		public void onSpeakBegin() {
			//			showTip("开始播放");
		}

		@Override
		public void onSpeakPaused() {
			//			showTip("暂停播放");
		}

		@Override
		public void onSpeakResumed() {
			//			showTip("继续播放");
		}

		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {
			// 合成进度
			//			mPercentForBuffering = percent;
			//			showTip(String.format(getString(R.string.tts_toast_format),
			//					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {
			// 播放进度
			//			mPercentForPlaying = percent;
			//			showTip(String.format(getString(R.string.tts_toast_format),
			//					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onCompleted(SpeechError error) {
			if (error == null) {
				//				showTip("播放完成");
			} else if (error != null) {
				showTip(error.getPlainDescription(true));
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

		}
	};

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}

	private void TTs() {
		String sayContext = "您有新的订单请及时处理";
		int code = mTts.startSpeaking(sayContext, mTtsListener);
		//		/** 
		//		 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
		//		 * text:要合成的文本，uri:需要保存的音频全路径，listener:回调接口
		//		*/
		//		String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
		//		int code = mTts.synthesizeToUri(text, path, mTtsListener);

		if (code != ErrorCode.SUCCESS) {
			if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
				//未安装则跳转到提示安装页面
				//mInstaller.install();
			}else {
				showTip("语音合成失败,错误码: " + code);	
			}
		}
	}
	/**友盟推送开发服务*/
	private void UmengPush()
	{
		//开启推送服务
		PushAgent mPushAgent = PushAgent.getInstance(MainActivity.this);
		mPushAgent.enable();
		//开启回掉处理
		//获取设备的device_token（可选）
		String device_token = UmengRegistrar.getRegistrationId(MainActivity.this);
		SharedPreferences spLogin=getSharedPreferences("spReg", MODE_PRIVATE);
		String token=spLogin.getString("token", "");

		//统计应用启动数据
		PushAgent.getInstance(MainActivity.this).onAppStart();
		//		TTs();
		//这是后台朗读，实例化一个SynthesizerPlayer
		//        SynthesizerPlayer player = SynthesizerPlayer.createSynthesizerPlayer(BluetoothActivity.this, APPID);
		//        //设置语音朗读者，可以根据需要设置男女朗读，具体请看api文档和官方论坛
		//        player.setVoiceName("vivixiaoyan");//在此设置语音播报的人选例如：vivixiaoyan、vivixiaomei、vivixiaoqi
		//        player.playText("您有新的订单，请及时处理", "ent=vivi21,bft=5",null);
		try {
			mPushAgent.addAlias(token, ALIAS_TYPE.BAIDU);
		} catch (e e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化监听。
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			if (code != ErrorCode.SUCCESS) {
				showTip("初始化失败,错误码："+code);
			} else {
				// 初始化成功，之后可以调用startSpeaking方法
				// 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
				// 正确的做法是将onCreate中的startSpeaking调用移至这里
			}		
		}
	};

	/**
	 * 参数设置
	 * @param param
	 * @return 
	 */
	private void setParam(){
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		// 根据合成引擎设置相应参数
		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
			// 设置在线合成发音人
			mTts.setParameter(SpeechConstant.VOICE_NAME,voicer);
		}else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
			// 设置本地合成发音人 voicer为空，默认通过语音+界面指定发音人。
			mTts.setParameter(SpeechConstant.VOICE_NAME,"");
		}
		//设置合成语速
		mTts.setParameter(SpeechConstant.SPEED, "50");
		//设置合成音调
		mTts.setParameter(SpeechConstant.PITCH, "50");
		//设置合成音量
		mTts.setParameter(SpeechConstant.VOLUME,"50");
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,"3");

		// 设置播放合成音频打断音乐播放，默认为true
		mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

		// 设置合成音频保存路径，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		mTts.setParameter(SpeechConstant.PARAMS,"tts_audio_path="+Environment.getExternalStorageDirectory()+"/test.pcm");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mTts.stopSpeaking();
		// 退出时释放连接
		mTts.destroy();
	}

	@Override
	protected void onResume() {
		//移动数据统计分析
		FlowerCollector.onResume(MainActivity.this);
		FlowerCollector.onPageStart(TAG);	
		super.onResume();
		this.mWakeLock.acquire(); 
	}
	@Override
	protected void onPause() {
		//移动数据统计分析
		FlowerCollector.onPageEnd(TAG);
		FlowerCollector.onPause(MainActivity.this);
		super.onPause();
		mWakeLock.release();
	}


	private long exitTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){   
			if((System.currentTimeMillis()-exitTime) > 2000){  
				Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();                                
				exitTime = System.currentTimeMillis();   
			} else {
				finish();
				System.exit(0);
			}
			return true;   
		}
		return super.onKeyDown(keyCode, event);
	}

	//	@Override
	//	public void run() {
	//	Process mLogcatProc = null;
	//	BufferedReader reader = null;
	//	try {
	//	  //获取logcat日志信息
	//	  mLogcatProc = Runtime.getRuntime().exec(new String[] { "logcat","com.umeng.message.proguard.l:I *:S" });
	//	  reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));
	//	  String line;
	//	  while ((line = reader.readLine()) != null) {
	//	    if (line.indexOf("status code : 200") > 0) {
	//	      //logcat打印信息在这里可以监听到
	//	      // 使用looper 把给界面一个显示
	//	      Looper.prepare();
	//	      TTs();
	//	      Toast.makeText(this, "监听到log信息", Toast.LENGTH_SHORT).show();
	//	      Looper.loop();
	//	    }
	//	  }
	//	} catch (Exception e) {
	//	  e.printStackTrace();
	//	}
	//	}


}

